<?php

namespace addons\shopro\model;

use think\Model;

/**
 * 预约抢购订单模型
 * Class RobOrderModel
 * @package addons\shopro\model
 */
class RobOrderModel extends Model
{
    protected $name = 'rob_order';

    /**
     * 获取列表
     * @param $params
     * @param int $rows
     * @param int $page
     * @param string $fields
     * @return array
     * @throws \think\exception\DbException
     */
    public function getLists($params, $rows = 20, $page = 1, $fields = '*')
    {
        // 条件搜索
        if (!empty($params['where'])) {
            $this->where($params['where']);
        } else {
            if (!empty($params['keyword'])) {
                switch ($params['type']) {
                    case 1 :
                        $this->where(['a.title' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                    case 2 :
                        $this->where(['b.nickname' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                    case 3 :
                        $this->where(['b.mobile' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                    case 4 :
                        $this->where(['c.title' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                }
            }
            if (!empty($params['is_use'])) {
                $this->where('a.is_use', '=', $params['is_use']);
            }
            if (!empty($params['is_rob'])) {
                $this->where('a.is_rob', '=', $params['is_rob']);
            }
            if (!empty($params['user_id'])) {
                $this->where('a.user_id', '=', $params['user_id']);
            }
            if (!empty($params['activity_id'])) {
                $this->where('a.activity_id', '=', $params['activity_id']);
            }
            // 时间范围查询
            if (!empty($params['start_time'])) {
                $this->where('a.create_time', '>=', strtotime($params['start_time']));
            }
            if (!empty($params['end_time'])) {
                $this->where('a.create_time', '<=', strtotime($params['end_time']));
            }
        }

        // 排序
        $order  = !empty($params['order']) ? $params['order'] : 'a.id DESC';
        $result = $this
            ->alias('a')
            ->join('user b', 'a.user_id = b.id')
            ->join('shopro_goods c', 'a.goods_id = c.id')
            ->field($fields)
            ->order($order)
            ->paginate($rows, false, [
                'page' => $page
            ]);

        $arr = [
            'list'      => [],
            'total'     => 0,
            'page'      => 1,
            'pageSize'  => $rows,
            'totalSize' => 0
        ];
        // 格式化数据信息
        if (!$result->isEmpty()) {
            $arr = [
                'list'      => $result->items(),
                'total'     => $result->total(),
                'page'      => $result->currentPage(),
                'pageSize'  => $result->listRows(),
                'totalSize' => $result->lastPage()
            ];
            if (!empty($arr['list'])) {
                foreach ($arr['list'] as &$v) {
                    if (!empty($v['activity_id'])) {
                        $endTime = Activity::where(['id' => $v['activity_id']])
                            ->value('endtime');
                        // 获取状态
                        $statusText = '已预约';

                        if ($endTime < time()) {
                            $statusText = $v->is_rob == 1 ? '获得抢购资格' : '未获得抢购资格';
                            if ($v->is_rob == 1 && $v->is_use == 1) {
                                $statusText = '已下单';
                            }
                        }

                        $v->status_text = $statusText;
                    }
                }
            }
        }

        return $arr;
    }

    /**
     * 预约
     * @param $user
     * @param $data
     * @return array
     */
    public static function add($user, $data)
    {
        // 是否已预约过了
        $id = self::
        where(['user_id' => $user->id, 'activity_id' => $data['id'], 'goods_id' => $data['goods_id']])
            ->value('id');
        if (!empty($id)) {
            return [
                'code' => 703,
                'msg'  => '您已经预约过了'
            ];
        }

        $order = [
            'user_id'        => $user->id,
            'activity_id'    => $data['id'],
            'goods_id'       => $data['goods_id'],
            'title'          => $data['title'],
            'activity_price' => $data['price'],
            'create_time'    => time()
        ];
        if (self::insertGetId($order)) {
            return [
                'code' => 200,
                'msg'  => '预约成功'
            ];
        } else {
            return [
                'code' => 700,
                'msg'  => '预约失败，请重试。'
            ];
        }
    }

    /**
     * 获取某条记录
     * @param $where
     * @return array|bool|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getItem($where, $fields = '*')
    {
        if (empty($where)) {
            $this->error = '参数不正确。';
            return false;
        }
        if (floor($where) > 0) {
            $where = ['id' => $where];
        }

        return $this->where($where)->field($fields)->find();
    }

    /**
     * 编辑
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        if (empty($data) || !is_array($data)) {
            $this->error = '参数不正确';
            return false;
        }

        if ($this->update($data)) {
            return true;
        } else {
            $this->error = '编辑出错了，请重新尝试。';
            return false;
        }
    }

    // 删除
    public function del($where)
    {
        if (empty($where)) {
            $this->error = '参数不正确';
            return false;
        }

        if ($this->where($where)->delete()) {
            return true;
        } else {
            $this->error = '删除出错了，请重新尝试。';
            return false;
        }
    }
}